<template>
  <BasicDrawer v-bind="$attrs" @register="registerShopWechatSetDrawer" destroyOnClose :title="title" width="40%" :showFooter="true" @ok="handleOk">
    <BasicTree ref="treeRef" title="公众号列表" search toolbar checkable checkStrictly :clickRowToExpand="true" :treeData="weChatTreeData" :fieldNames="{ key: 'weChatId', title: 'weChatName' }" :checkedKeys="wechatCheckedKeys" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, unref } from 'vue';
import { BasicTree, TreeActionType, TreeItem } from '@apps/antd-admin/src/components/tree';
import { BasicDrawer, useDrawerInner } from '@apps/antd-admin/src/components/drawer';
import { querySetWechat, setWechat } from '../data/api';
import { weChatList } from '@apps/ant-bus/src/views/business/platformManage/wechat/data/api';
// 声明Emits
const emit = defineEmits(['register', 'success']);
let title = ref('');
let shopId = ref('');
const weChatTreeData = ref<TreeItem[]>([]);
let wechatCheckedKeys = ref([]);
const treeRef = ref<Nullable<TreeActionType>>(null);
const [registerShopWechatSetDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  let record = data.record;
  title.value = record.shopName + '-上架公众号';
  shopId.value = record.shopId;
  weChatTreeData.value = (await weChatList()) as unknown as TreeItem[];
  wechatCheckedKeys.value = await querySetWechat({ shopId: shopId });
});

function getTree() {
  const tree = unref(treeRef);
  if (!tree) {
    throw new Error('tree is null!');
  }
  return tree;
}

/**
 * 确定按钮事件
 */
async function handleOk() {
  try {
    setDrawerProps({ confirmLoading: true });
    const keys: any = getTree().getCheckedKeys();
    let selectKeys = keys.join(',');
    await setWechat({
      goodsId: shopId,
      weChatIds: selectKeys,
    });
    //关闭抽屉
    closeDrawer();
  } catch (err) {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
